package com.mycom.core2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author xp
 *         Created on 2018/2/27
 */
public class TcpClient {
    private static final Logger log = LoggerFactory.getLogger(TcpClient.class);

    public static String host = AppInit.config.getProperty("client_server_ip");
    public static int port = Integer.parseInt(AppInit.config.getProperty("client_server_port"));

    public void start() {
        // 配置客户端的NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        log.info("【TCP】客户端服务启动中，端口号：" + port);
        try {
            //Netty的引导类，用于简化开发
            Bootstrap b = new Bootstrap();

            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new TcpClientInitializer());

            // 连接服务端
            ChannelFuture future = b.connect(host, port).sync();
            if (future.isSuccess()) {
                log.info("【TCP】启动netty 客户端客户端成功, 端口号" + port);
            }
            // 这里是客户端发送的消息
            future.channel().writeAndFlush("Hello Netty Server ,I am a common client");
        } catch (InterruptedException e) {
            log.error("====Tcp-client 启动失败：", e);
        } finally {

        }
    }
}
